const pagesInfo = {
  login: {
    key: "Login",
    url: "pages/account/login/login",
    desc: "登录"
  },
  register: {
    key: "Register",
    url: "pages/account/register/register",
    desc: "注册"
  },
  password: {
    key: "Password",
    url: "pages/account/password/password",
    desc: "找回密码"
  },
  phoneauth: {
    key: "PhoneAuth",
    url: "pages/account/phoneauth/index",
    desc: "手机授权"
  },
  index: {
    key: "Home",
    url: "pages/index",
    desc: "首页"
  },
  customIndex: {
    key: "CustomIndex",
    url: "pages/custom",
    desc: "自定义首页"
  },

  productList: {
    key: "ProductList",
    url: "packageStore/pages/product/list/list",
    desc: "商品列表"
  },
  productDetail: {
    key: "ProductDetail",
    url: "packageStore/pages/product/detail/detail",
    desc: "商品详情"
  },
  productCommentList: {
    key: "ProductCommentList",
    url: "packageStore/pages/product/comment/comment",
    desc: "商品评论列表"
  },
  scantGoods: {
    key: "ScantGoods",
    url: "packageStore/pages/purchase/scantygoods/scantygoods",
    desc: "缺货登记"
  },
  photoRecords: {
    key: "TakeOrderRecord",
    url: "packageStore/pages/purchase/photorecords/index",
    desc: "拍照下单记录"
  },
  panicBuyList: {
    key: "PanicBuyList",
    url: "packageStore/pages/market/panicbuy/list",
    desc: "限时特价列表"
  },
  panicBuyDeail: {
    key: "PanicBuyDeail",
    url: "packageStore/pages/market/group/detail",
    desc: "限时特价列表"
  },

  groupList: {
    key: "GroupList",
    url: "packageStore/pages/market/group/list",
    desc: "拼团列表"
  },
  groupDetail: {
    key: "GroupDetail",
    url: "packageStore/pages/market/group/detail",
    desc: "拼团详情"
  },

  presellList: {
    key: "PresellList",
    url: "packageStore/pages/market/group/list",
    desc: "预售列表"
  },
  presellDeail: {
    key: "PresellDeail",
    url: "packageStore/pages/market/group/detail",
    desc: "预售详情"
  },
  promotionlist: {
    key: "PromotionList",
    url: "packageStore/pages/market/promotions/list",
    desc: "促销大全"
  },
  promotionDetail:{
    key:"PromotionDetail",
    url:"packageStore/pages/market/promotions/detail",
    desc:"促销详情"
  },
  classify: {
    key: "NewCategory",
    url: "pages/store/purchase/classify/classify",
    desc: "分类"
  },
  category: {
    key: "Directory",
    url: "pages/store/purchase/fast/fast",
    desc: "目录"
  },
  favorite: {
    key: "Collection",
    url: "pages/store/purchase/fast/fast",
    desc: "收藏"
  },
  offenBuy: {
    key: "Commodity",
    url: "pages/store/purchase/fast/fast",
    desc: "常购"
  },
  repurchase: {
    key: "LongOrder",
    url: "pages/store/purchase/fast/fast",
    desc: "复购"
  },
  scan: {
    key: "Scan",
    url: "pages/store/purchase/fast/fast",
    desc: "扫码"
  },
  takePhoto:{
    key: "TakeOrder",
    url: "pages/store/purchase/fast/fast",
    desc: "拍照下单"
  },
  cart: {
    key: "Cart",
    url: "pages/store/purchase/cart/cart",
    desc: "购物车"
  },
  orderConfirm: {
    key: "OrderConfirm",
    url: "pages/store/purchase/confirm/confirm",
    desc: "订单确认"
  },
  groupConfirm: {
    key: "GroupConfirm",
    url: "pages/store/purchase/groupconfirm/confirm",
    desc: "拼团确认"
  },
  presellConfirm: {
    key: "PresellConfirm",
    url: "pages/store/purchase/groupconfirm/confirm",
    desc: "预售确认"
  },
  cashier: {
    key: "Cashier",
    url: "packageCashier/pages/pay/pay",
    desc: "收银台"
  },
  paySuccess: {
    key: "PaySuccess",
    url: "packageCashier/pages/success/success",
    desc: "支付成功"
  },
  photoSuccess: {
    key: "PhotoSuccess",
    url: "packageCashier/pages/photosuccess/index",
    desc: "提交成功"
  },
  center: {
    key: "Mine",
    url: "pages/store/profile/index",
    desc: "我的"
  },
  orderList: {
    key: "BuyOrders",
    url: "packageStore/pages/purchase/list/list",
    desc: "采购订单列表"
  },
  orderDetail: {
    key: "BuyOrderDetail",
    url: "packageStore/pages/purchase/detail/detail",
    desc: "采购订单详情"
  },
  orderOffine: {
    key: "orderOffine",
    url: "packageStore/pages/purchase/orderoffine/detail",
    desc: "采购订单详情"
  },
  orderGoodsList: {
    key: "OrderGoodsList",
    url: "packageStore/pages/purchase/goodslist/goodslist",
    desc: "商品清单"
  },
  logisticsTracking: {
    key: "LogisticsTracking",
    url: "packageStore/pages/purchase/trade/trade",
    desc: "物流跟踪"
  },
  retreatList: {
    key: "RetreatList",
    url: "packageStore/pages/retreat/list/list",
    desc: "退换货列表"
  },
  retreatDetail: {
    key: "RetreatDetail",
    url: "packageStore/pages/retreat/detail/detail",
    desc: "退换货详情"
  },
  applyRetreat: {
    key: "ApplyRetreat",
    url: "packageStore/pages/retreat/apply/apply",
    desc: "申请退换货"
  },
  commentList: {
    key: "CommentList",
    url: "packageStore/pages/comment/list/list",
    desc: "评论列表"
  },
  commentDetail: {
    key: "CommentDetail",
    url: "packageStore/pages/comment/detail/detail",
    desc: "评论详情"
  },
  comment: {
    key: "Comment",
    url: "packageStore/pages/comment/comment/index",
    desc: "评论页面"
  },
  integral: {
    key: "Integral",
    url: "packageStore/pages/finance/intergral/intergral",
    desc: "采购积分"
  },
  billList: {
    key: "BillList",
    url: "packageStore/pages/credit/bill_list/bill_list",
    desc: "账单列表"
  },
  billDetail: {
    key: "BillDetail",
    url: "packageStore/pages/credit/bill_detail/bill_detail",
    desc: "账单详情"
  },
  waitBillList: {
    key: "WaitBillList",
    url: "packageStore/pages/credit/wait_bill_list/wait_bill_list",
    desc: "待还款账单列表"
  },
  billDetailItem: {
    key: "BillDetailItem",
    url: "packageStore/pages/credit/bill_detail_item/bill_detail_item",
    desc: "账单详情"
  },
  billPayComfirm: {
    key: "BillPayComfirm",
    url: "packageStore/pages/credit/bill_pay/bill_pay",
    desc: "账单支付确认"
  },
  myCouponList: {
    key: "MyCouponList",
    url: "packageStore/pages/purchase/coupon/coupon",
    desc: "我的优惠券"
  },
  receivedCouponList: {
    key: "Coupons",
    url: "packageStore/pages/market/coupon/list",
    desc: "在线领取优惠券"
  },
  couponDetail: {
    key: "CouponDetail",
    url: "packageStore/pages/market/coupon/detail",
    desc: "优惠券详情"
  },
  recharge: {
    key: "Recharge",
    url: "packageStore/pages/finance/recharge/recharge",
    desc: "预存款充值"
  },
  rechargeDetail: {
    key: "RechargeDetail",
    url: "packageStore/pages/finance/recharge_detail/recharge_detail",
    desc: "预存款明细"
  },
  arrears: {
    key: "Arrears",
    url: "packageStore/pages/purchase/arrears/arrears",
    desc: "欠款订单列表"
  },
  dealing: {
    key: "Dealing",
    url: "packageStore/pages/purchase/dealing/dealing",
    desc: "往来对账"
  },
  dealingOffline: {
    key: "DealingOffline",
    url: "packageStore/pages/purchase/dealing_offline/dealing_offline",
    desc: "线下往来"
  },
  userAccount:{
    key: "UserAccount",
    url: "packageStore/pages/purchase/useraccount/index",
    desc: "我的账户"
  },
  addAccount:{
    key: "AddAccount",
    url: "packageStore/pages/purchase/addaccount/index",
    desc: "添加账户"
  },
  myGroupList: {
    key: "GroupOrders",
    url: "packageStore/pages/purchase/grouplist/grouplist",
    desc: "我的拼团列表"
  },
  myGroupDetail: {
    key: "GroupOrderDetail",
    url: "packageStore/pages/purchase/groupdetail/groupdetail",
    desc: "我的预售详情"
  },

  myPresellList: {
    key: "BookOrders",
    url: "packageStore/pages/purchase/grouplist/grouplist",
    desc: "我的预售列表"
  },
  myPresellDeatil: {
    key: "BookOrderDetail",
    url: "packageStore/pages/purchase/groupdetail/groupdetail",
    desc: "我的预售详情"
  },

  addressList: {
    key: "AddressList",
    url: "packageStore/pages/profile/address/list",
    desc: "收货地址"
  },
  invoiceList: {
    key: "InvoiceList",
    url: "packageStore/pages/profile/invoice/list",
    desc: "发票抬头"
  },
  selfList: {
    key: "SelfList",
    url: "packageStore/pages/profile/selfAddress/list",
    desc: "自提点列表"
  },
  perfect: {
    key: "Perfect",
    url: "packageStore/pages/perfect/perfect",
    desc: "完善信息"
  },
  business: {
    key: "Business",
    url: "packageStore/pages/perfect/business/list",
    desc: "经营范围"
  },
  passwordModify: {
    key: "PasswordModify",
    url: "packageStore/pages/profile/password/password",
    desc: "登录密码修改"
  },
  subMenu:{
    key:"subMenu",
    url: "packageStore/pages/profile/subMenu/index",
    desc: "子账号菜单"
  },
  addSubAccount:{
    key:"addSubAccount",
    url: "packageStore/pages/profile/addSubAccount/index",
    desc: "添加子账号"
  },
  payPwdModify: {
    key: "ChangePayPass",
    url: "packageStore/pages/profile/paypwd/paypwd",
    desc: "支付密码修改"
  },
  findPayPwd: {
    key: "FindPayPwd",
    url: "packageStore/pages/profile/findpaypwd/findpaypwd",
    desc: "支付密码修改"
  },
  wxAccountList: {
    key: "WxAccountList",
    url: "packageStore/pages/profile/wxaccount/wxaccount",
    desc: "微信账号列表"
  },
  setting: {
    key: "Setting",
    url: "packageStore/pages/profile/setting/setting",
    desc: "设置"
  },
  clerkCard: {
    key: "ClerkCard",
    url: "packageStore/pages/profile/clerkcard/clerkcard",
    desc: "业务员"
  },
  financeAccountList: {
    key: "FinanceAccountList",
    url: "packageStore/pages/finance/account/account",
    desc: "资金帐户列表"
  },
  msgList: {
    key: "MessageList",
    url: "packageStore/pages/profile/msg/list",
    desc: "消息列表"
  },
  msgDetail: {
    key: "MessageInfo",
    url: "packageStore/pages/profile/msg/detail",
    desc: "消息详情"
  },
  noticeDetail: {
    key: "NoticeDetail",
    url: "pages/cms/notice_detail",
    desc: "公告详情"
  },
  squaredPaper: {
    key: "SquaredPaper",
    url: "pages/game/squared-paper/index",
    desc: "九宫格"
  },
  gameRecordList: {
    key: "GameRecordList",
    url: "pages/game/record/index",
    desc: "游戏记录列表"
  },
  transfer: {
    key: "Transfer",
    url: "pages/common/container/index",
    desc: "中转页面"
  },
  interim: {
    key: "Transfer",
    url: "pages/common/interim/index",
    desc: "临时页面"
  },
  distributionApply:{
    key:'DistributionApply',
    url:"packageDistribution/pages/apply/apply",
    desc:"申请分销"
  },
  distributionMain:{
    key:'DistributionMain',
    url:"packageDistribution/pages/main/main",
    desc:"分销中心"
  },
  distributionCashOut:{
    key:'DistributionCashOut',
    url:"packageDistribution/pages/cashOut/index",
    desc:"提现"
  },
  distributionCashOutList:{
    key:'DistributionCashOutList',
    url:"packageDistribution/pages/cashOut/list",
    desc:"提现记录"
  },
  distributionCommission:{
    key:'DistributionCommission',
    url:"packageDistribution/pages/commission/index",
    desc:"分销佣金"
  },
  distributionOrderList:{
    key:'DistributionOrderList',
    url:"packageDistribution/pages/order/list",
    desc:"分销订单"
  },
  distributionOrderDetail:{
    key:'DistributionOrderDetail',
    url:"packageDistribution/pages/order/detail",
    desc:"商品清单"
  },
  distributionSub:{
    key:'DistributionSub',
    url:"packageDistribution/pages/sub/index",
    desc:"下级客户"
  },
  distributionCard:{
    key:'DistributionCard',
    url:"packageDistribution/pages/card/index",
    desc:"我的名片"
  },
  distributionRank:{
    key:'DistributionRank',
    url:"packageDistribution/pages/rank/index",
    desc:"我的排名"
  },
  distributionInvite:{
    key:'DistributionInvite',
    url:"pages/account/invite/index",
    desc:"邀请加入"
  },
  live:{
    key:'Live',
    url:"packageStore/pages/market/live/live",
    desc:"直播"
  },
  postdetail:{
    key:'postDetail',
    url:"packageCommunity/pages/articleDetail/index",
    desc:"帖子详情"
  },
  SureOrderDetail:{
    key:'SureOrderDetail',
    url:"packageStore/pages/purchase/detail/detail",
    desc:"订单详情"
  },
  setmeal:{
    key:'setmeal',
    url:"pages/store/purchase/setmeal/setmeal",
    desc:"优惠套餐"
  },
  notDetail:{
    key:'notDetail',
    url:"packageCommunity/pages/noticeDetail/index",
    desc:"公告详情"
  },
  videoDetail:{
    key:'videoDetail',
    url:"packageCommunity/pages/videoDetail/index",
    desc:"视频"
  },
  chooseCustomer: {
    key: 'chooseCustomer',
    url: 'packageCustomer/pages/chooseCustomer/index',
    desc: '选择客户'
  },
  aboutApplication: {
    key: 'aboutApplication',
    url: 'packageStore/pages/profile/aboutApplication/index',
    desc: '关于程序'
  },
  setFontSize: {
    key: 'setFontSize',
    url: 'packageStore/pages/profile/fontSizeSetting/index',
    desc: '字体大小设置'
  },
  userSetting: {
    key: 'userSetting',
    url: 'packageStore/pages/profile/userSetting/userSetting',
    desc: '用户设置页面'
  },
  orderDeliveryInfo: {
    key: 'orderDeliveryInfo',
    url: 'packageStore/pages/purchase/orderDeliveryInfo/orderDeliveryInfo',
    desc: '订单发货信息列表'
  },
  chooseProductGift: {
    key: 'chooseProductGift',
    url: 'packageStore/pages/purchase/chooseProductGift/chooseProductGift',
    desc: '选择赠品'
  },
  orderOffineRetreat: {
    key: "orderOffineRetreat",
    url: "packageStore/pages/purchase/orderOffineRetreat/detail",
    desc: "erp订单退换货详情"
  },
  mustBuyProductList: {
    key: "mustBuyProductList",
    url: "packageStore/pages/market/mustBuyProductList/mustBuyProductList",
    desc: "促销及优惠券等页面，必买商品展示列表"
  },
}
/**
 *
 * 这里重新封装了导航方法，navigate、redirect、switchTab、reLaunch分别对应着微信的导航方法，
 * 与微信提供的API不同的是，这里参数data里面的path是静态配置路径，即app.json文件的页面路径；
 * params为链接查询参数；
 * @example
 * navigate({
 *      path:'pages/index/index',
 *      params:{
 *          id:123
 *      }
 * });//跳转到index页面，index页面的options可以读取到id。
 *
 */
const router = (function() {

  let CURRENT_ROUTE = "";

  function route(data, method) {
    try {
      const length = getCurrentPages().length;
      const currentRoute = getCurrentPages()[length - 1].route;
      if (currentRoute == CURRENT_ROUTE) {
        //防止在用一个事件下多次导航到同一个页面
        return;
      }
      if (pagesInfo[data.path]) {
        data.path = pagesInfo[data.path].url;
      }

      const pathIndex = currentRoute.split('/').length;
      const path = joinPath(pathIndex, data.path)
      const url = joinParams(data.params, path)

      CURRENT_ROUTE = currentRoute;
      clearCurrent();

      if (data.path == currentRoute) {
        let currentOptions = getCurrentPages()[length - 1].options;
        if (joinParams("", path) == joinParams("",currentOptions))
        {//不能导航到自己
          return;
        }
      }

      const obj = {
        ...data,
        url
      };

      //调用微信的router方法
      wx[method].call(null, obj);

    } catch (e) {
      console.log(`error in router: +${e}`)
    }
  }

  function joinPath(index, url) {
    let str = ""
    for (let i = 0; i < index - 1; i++) {
      str += "../";
    }
    return str + url;
  }

  function joinParams(params, url) {

    //没有参数，直接返回url
    if (!params) {
      return url;
    }

    let keys = Object.keys(params);
    let finalUrl = ""

    //参数没有key 返回url
    if (keys.length == 0) {
      return url;

    } else {

      //url没有拼接 ？
      if (url.indexOf("?") === -1) {
        finalUrl = keys.reduce((url, key) => {
          return url + key + "=" + params[key] + "&";
        }, url + "?");
      } else {

        //url以 ？ 号结尾
        if (url.endsWith("?")) {
          finalUrl = keys.reduce((url, key) => {
            return url + key + "=" + params[key] + "&";
          }, url);

        } else {

          //url以 & 结尾
          if (url.endsWith("&")) {
            finalUrl = keys.reduce((url, key) => {
              return url + key + "=" + params[key] + "&";
            }, url);

          } else {

            //直接拼接
            finalUrl = keys.reduce((url, key) => {
              return url + key + "=" + params[key] + "&";
            }, url + "&")
          }
        }
      }
    }

    return finalUrl.endsWith("&") ?
      finalUrl.slice(0, finalUrl.length - 1) :
      finalUrl;
  }

  function clearCurrent() {
    setTimeout(() => {
      CURRENT_ROUTE = "";
    }, 0);
  }

  return {
    /**
     * 封装后的 navigate 方法
     * @param {path：静态路径，params: {}}
     */
    navigateBack(data = {},refreshPage=false) {
      if (data) {
        const length = getCurrentPages().length;
        var prePage = getCurrentPages()[length - 2]
        if (prePage) {
          prePage.setData(data);
          if (refreshPage)
          {
            prePage.refreshPage();
          }
        }
      }
      wx.navigateBack()
    },
    /**
     * 封装后的 redirect 方法
     * @param {path：静态路径，params: {}}
     */
    reLaunch(data = {
      path = "",
      params
    } = {}) {
      return route(data, "reLaunch");
    },
    /**
     * 封装后的 switchTab 方法
     * @param {path：静态路径，params: {}}
     */
    switchTab(data = {
      path = "",
      params
    } = {}) {
      return route(data, "switchTab");
    },
    /**
     * 封装后的 reLaunch 方法
     * @param {path：静态路径，params: {}}
     */
    redirect(data = {
      path = "",
      params
    } = {}) {
      return route(data, "redirectTo")
    },
    /**
     * 设置上一页面的数据，并返回
     */
    navigate(data = {
      path = "",
      params
    } = {}) {
      return route(data, "navigateTo")
    },
    bindPrePageData(data = {
      keys
    }) {
      if (data.keys) {
        const pages = getCurrentPages();
        const length = pages.length;
        const current = pages[pages.length - 1]; //当前页
        const prePage = pages[length - 2]; //上一页
        const preData = prePage.data;
        const myData = {};
        const keys = data.keys.split(',');
        for (const key in preData) {
          if (key == "screenData") {
            myData[key] = preData[key];
          }
        }
        if (preData) {
          current.setData(myData);
        }
      }
    },
    joinParams(data = {
      path = "",
      params
    } = {}) {
      return joinParams(data.params, data.path)
    }
  }
})();
module.exports={
  pagesInfo,
  router
}